﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ShortcutToolbox.Core
{
    public static class Plugins
    {
        static Plugins()
        {
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(onAssemblyResolve);
        }

        public static IList<IPlugin> GetPlugins()
        {
            List<IPlugin> list = new List<IPlugin>();
            string[][] folders = new string[][] {
                new string[]{ "plugins", "*.dll" },
                new string[]{ Utils.GetUserProfileDirectoryPath("plugins"), "*.dll" },
            };

            foreach (string[] item in folders)
            {
                if (!Directory.Exists(item[0]))
                    continue;
                string[] files = Directory.GetFiles(item[0], item[1]);
                if (files == null)
                    continue;
                foreach (string file in files)
                {
                    try
                    {
                        Assembly assembly = Assembly.LoadFile(new FileInfo(file).FullName);
                        if (assembly != null)
                        {
                            foreach (Type t in assembly.ExportedTypes)
                            {
                                if (t.GetInterface(typeof(IPlugin).FullName) != null
                                    && !t.IsAbstract
                                    && t.GetInterface(typeof(IInnerPlugin).FullName) == null)
                                {
                                    IPlugin plugin = t.GetConstructor(Type.EmptyTypes).Invoke(null) as IPlugin;
                                    list.Add(plugin);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Error(ex);
                    }
                }
            }
            return list;
        }

        static Assembly onAssemblyResolve(object sender, ResolveEventArgs e)
        {
            string[] folders = new string[] {
                "plugins",
                Utils.GetUserProfileDirectoryPath("plugins"),
            };
            string assmName = e.Name.Substring(0, e.Name.IndexOf(","));
            if(e.RequestingAssembly != null)
            {
                string dir = Path.GetDirectoryName(e.RequestingAssembly.Location);
                string path = Path.Combine(dir, assmName + ".dll");
                if(File.Exists(path))
                    return Assembly.LoadFrom(path);
            }
            foreach (string folder in folders)
            {
                string path = Path.Combine(folder, assmName + ".dll");
                if (File.Exists(path))
                    return Assembly.LoadFrom(path);
            }
            return null;
        }
    }
}
